package com.syni.mdd.yhd.common.all.listen.flow;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.sjb.common.component.utils.common.utils.AppConfig;
import com.syni.mdd.sjb.common.component.utils.common.utils.ParamsMap;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.dto.requestDto.groupChart.GroupChatReDto;
import com.syni.mdd.yhd.common.all.entity.BmsBusiness;
import com.syni.mdd.yhd.common.all.entity.BmsBusinessFlow;
import com.syni.mdd.yhd.common.all.entity.cdn.BmsCdnData;
import com.syni.mdd.yhd.common.all.entity.flow.FlowDocument;
import com.syni.mdd.yhd.common.all.entity.groupChat.BmsDxGroupChat;
import com.syni.mdd.yhd.common.all.service.BmsBusinessFlowService;
import com.syni.mdd.yhd.common.all.service.BmsDxGroupChatService;
import com.syni.mdd.yhd.common.all.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @className OrderListener
 * @description TOO
 * @Author cfx
 * @DATE 2019/8/8 15:46
 * @VERSION 1.0
 **/
@Component
public class BusinessFlowListener implements ApplicationListener<BusinessFlowEvent> {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    BmsBusinessFlowService bmsBusinessFlowService;

    @Value("${app.headImg.tmpUrl}")
    private String tempUrl;

    public static String downUrl = "https://openapi.esign.cn/v1/signflows/%s/documents";

    @Override
    @Async
    public void onApplicationEvent(BusinessFlowEvent businessFocusEvent) {
        ParamsMap paramsMap = new ParamsMap();
        Map<String, Object> tokenMap = bmsBusinessFlowService.getToken(paramsMap);
        String token = null;
        if(tokenMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(tokenMap.get("status").toString())){
           Map<String,Object> tokenData = (Map<String, Object>) tokenMap.get("data");
           token = tokenData.get("token").toString();
        }
        if(StringUtils.isNotBlank(token)) {
            BmsBusinessFlow bmsBusinessFlow = businessFocusEvent.getBmsBusinessFlow();
            if (bmsBusinessFlow.getFlowStatus() == Constants.STATUS_1) {
                if (bmsBusinessFlow.getFlowId() != null && StringUtils.isBlank(bmsBusinessFlow.getFlowData())) {
                    //下载pdf
                    String trueUrl = String.format(downUrl, bmsBusinessFlow.getFlowId());
                    Map<String, Object> paramsMaps = new HashMap<>();
                    paramsMaps.put("X-Tsign-Open-App-Id", AppConfig.getProperty(Constants.FLOW_APP_ID));
                    paramsMaps.put("X-Tsign-Open-Token", token);
                    String reponseBody = RestTemplateUtils.getForEntity(trueUrl,new HashMap<>(),paramsMaps);
                    if (StringUtils.isNotBlank(reponseBody)) {
                        Map<String, Object> reponseBodyMap = JSON.parseObject(reponseBody);
                        if(reponseBodyMap.containsKey("code") && Integer.parseInt(reponseBodyMap.get("code").toString()) == 0){
                            //判断成功
                            //bmsBusinessFlow.setFlowData(reponseBodyMap.get("data").toString());
                            FlowDocument flowDocument = JSON.parseObject(bmsBusinessFlow.getFlowData(),FlowDocument.class);
                            String fileUrl = flowDocument.getDocs().get(0).getFileUrl();
                            String saveUrl = NetFileUtil.downLoadFromUrl(fileUrl,"tmp.pdf",tempUrl);
                            //将pdf转成图片
                            List<String> imgUrlList = PictureUtil.pdf2png(saveUrl,"jpg");
                            List<String> uploadUrls = new ArrayList<>();
                            if(imgUrlList != null && imgUrlList.size() > 0) {
                                for(String img : imgUrlList) {
                                    //bmsBusinessFlow.setFlowStatus(Constants.STATUS_2);
                                    if(StringUtils.isNotBlank(img)) {
                                        BmsCdnData bmsCdnData = CDNUtils.uploadCOS(CDNUtils.bucketName, "/flow", img, CDNUtils.width, CDNUtils.height);
                                        if (bmsCdnData != null) {
                                            uploadUrls.add(bmsCdnData.getSourceUrlBig());
                                        }
                                    }
                                }
                                flowDocument.getDocs().get(0).setFileImgUrl(uploadUrls);
                                bmsBusinessFlow.setFlowStatus(Constants.STATUS_2);
                                bmsBusinessFlow.setFlowData(JSON.toJSONString(flowDocument));
                            }
                        }
                    }
                    //NetFileUtil.downLoadFromUrl(paramsMaps)
                    bmsBusinessFlowService.getBaseDao().save(bmsBusinessFlow);
                }
            }
        }

    }
}
